import * as CSJS from '@intercom/messenger-js-sdk';
import { Hex as encHex } from 'crypto-es/lib/core';
import { HmacSHA256 } from 'crypto-es/lib/sha256';
import type { MyUserDetail } from '~/api/services/main.api';
import { useAuthed } from '~/composables/useAuthed';

type CSConfig = Parameters<typeof CSJS.Intercom>[0];

const APPID = 'qqn6wp0r';
const SECRETKEY = 'iz8siXQSPDDG85tpNSEfEVO5tzfoSHAZ5XQAu31Y';

function getCSConfig(user?: MyUserDetail): CSConfig | null {
  if (!user)
    return null;
  const avatarUrl = useAppStore().getCdnResPath('avatar', user.avatar);
  const hash = HmacSHA256(user.uid.toString(), SECRETKEY).toString(encHex);
  return {
    app_id: APPID,
    hide_default_launcher: true,
    user_id: user.uid,
    name: user.nickname,
    email: user.email,
    created_at: dayjs(user.reg_time).unix(),
    avatar: { type: 'avatar', image_url: avatarUrl },
    language_override: user.lang,
    // session_duration: 5 * 1000,
    user_hash: hash,
  };
}

const currentConfig = reactive<{ user?: MyUserDetail; config?: CSConfig }>({
  user: void 0,
  config: void 0,
});

function clearConfig() {
  currentConfig.user = void 0;
  currentConfig.config = void 0;
}

function generateCSFn<T extends (arg: CSConfig) => void>(fn: T) {
  return (user?: MyUserDetail) => {
    const config = getCSConfig(user);
    if (config) {
      fn(config);
      currentConfig.config = config;
      currentConfig.user = user;
    }
  };
}

const create = generateCSFn(CSJS.Intercom);

const update = generateCSFn(CSJS.update);

function setup(newUser?: MyUserDetail, oldUser?: MyUserDetail) {
  if (newUser === void 0 && oldUser?.uid) {
    clearConfig();
    return;
  }
  if (oldUser === void 0 && newUser?.uid)
    create(newUser);

  else if (newUser && oldUser && newUser.uid !== oldUser.uid)
    update(newUser);
}

function getCustomerInfo(user?: MyUserDetail) {
  if (!user)
    return null;
  return {
    userid: user.uid || '',
    username: user.nickname || '',
    email: user.email || '',
    avatar: useAppStore().getCdnResPath('avatar', user.avatar),
    level: user.level || 0,
  };
}

function showLivechat() {
  const LC = (window as any).LC_API;
  const LCW = (window as any).LiveChatWidget;
  if (!LC?.is_loaded?.()) {
    LCW?.init?.();
  }
  const uInfo = getCustomerInfo(useUserStore().userInfo);
  if (uInfo) {
    LCW?.call?.('update_session_variables', uInfo);
    LC?.set_custom_variables?.([uInfo]);
    LC?.call?.('update_session_variables', uInfo);
  }
  if (uInfo?.username) {
    LCW?.call?.('set_customer_name', uInfo.username);
    LC?.set_visitor_name?.(uInfo.username);
  }
  if (uInfo?.email) {
    LCW?.call?.('set_customer_email', uInfo.email);
    LC?.set_visitor_email?.(uInfo.email);
  }
  const fn = useAppBreakpoints().ltTablet ? LC?.open_mobile_window : LC?.open_chat_window;
  fn?.();
}

/**
 * 打开客服
 * return 客服类型：0 关闭， 1 telegram， 2 online，undefined 不打开  3 livechat  4 Agent telegram
 */
async function showCs() {
  const appStore = useAppStore();
  const userStore = useUserStore();
  if (!toValue(appStore.handshake)) {
    await appStore.handshakeQry.refetch();
  }

  const tgCsUrl = toValue(appStore.handshake)?.telegram_customer_id;

  if (toValue(appStore.isAgent) && tgCsUrl) {
    window.open(tgCsUrl);
    return 4;
  }

  showLivechat();
  return 3;

  const csType = toValue(appStore.handshake)?.customer_type;

  if (csType === 0) {
    antdMessage.warning($t('jNfOsbJc0gj41A3XvQjcx'));
    return 0;
  }

  if (csType === 1 && tgCsUrl) {
    window.open(tgCsUrl);
    return 1;
  }

  if (csType === 2) {
    const authed = useAuthed();
    if (!toValue(userStore.userInfo) && authed.value) {
      await userStore.userInfoQry.refetch();
    }
    if (!authed.value && !currentConfig.user) {
      antdMessage.warning($t('f916l_0NAcf4GUVhTRg'));
      return void 0;
    }
    const fn = currentConfig.user ? update : create;
    fn(toValue(userStore.userInfo));
    CSJS.show();
    return 2;
  }

  return void 0;
}

export function useCS() {
  return {
    create,
    setup,
    update,
    hide: CSJS.hide,
    show: showCs,
    showMsg: CSJS.showMessages,
    clear: clearConfig,
  };
}

export default useCS();
